<template>
  <div class="monthly-container">
    <div class="filter-container flex-row">
      <el-input
        v-model="tableListQuery.keyword"
        placeholder="请输入搜索内容"
        prefix-icon="el-icon-search"
        style="width:200px;"
        class="filter-item"
      />
      <el-button class="filter-item" type="primary" @click="getBillList">搜索</el-button>
      <el-date-picker
        v-model="tableListQuery.billDate"
        type="month"
        placeholder="请选择月份"
        class="filter-item"
        style="width:150px;margin-left:15px;"
        @change="getBillList"
      />
      <el-select
        v-model="tableListQuery.status"
        placeholder="请选择发出状态"
        clearable
        class="filter-item"
        style="width:150px;margin-left:15px;"
        @change="getBillList"
      >
        <el-option label="未发出" :value="0" />
        <el-option label="已发出" :value="1" />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        style="margin-left:auto;"
        @click="addBillClick"
      >新增</el-button>
    </div>
    <div class="bill-overview">
      <span style="margin-right:20px;">总收入：${{ extraData.totalIn }}</span><span style="margin-right:20px;">总支出：${{ extraData.totalOut }}</span><span>结余：${{ extraData.settlementFee }}</span>
    </div>
    <monthly-table :bill-list="billList" @handleDel="handleDel" @handleDetail="billDetail" @handleEdit="edit" />
    <br>
    <el-pagination
      :v-show="total > 0"
      background
      :current-page="tableListQuery.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="tableListQuery.limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog
      title=""
      width="1073px"
      custom-class="myDigo inputTop"
      :show-close="false"
      :visible.sync="showAdd"
      destroy-on-close
      @closed="addDialogClosed"
    >
      <h2 v-if="!isEdit">新增月账单<i class="el-icon-close" @click="close" /></h2>
      <h2 v-if="isEdit">编辑月账单<i class="el-icon-close" @click="close" /></h2>
      <div class="digoDiv">
        <el-form
          v-if="showAdd"
          ref="billForm"
          :model="billForm"
          :label-position="'left'"
          :rules="rules"
          label-width="64px"
          class="formDiv"
        >
          <el-form-item label="房产">
            <div class="flex-row">
              <div style="flex:1;">
                <el-select v-model="billForm.houseId" filterable placeholder="请输入关键字：房产（地址/ID）" style="width:100%" @change="selectHouse">
                  <el-option
                    v-for="item in houseList"
                    :key="item.id"
                    :label="item.address"
                    :value="item.id"
                  />
                </el-select>
              </div>
              <div style="margin-left:10px">
                <el-button type="info" plain class="form-btn" @click="getLastBill(billForm.houseId)">查看最近一个月账单</el-button>
              </div>
            </div>
          </el-form-item>

          <div class="flex-row borbtoonline">
            <el-form-item label="账单月份" style="margin-right:20px">
              <el-date-picker
                v-model="billForm.billDate"
                type="month"
                placeholder="请选择账单月份"
                style="width:150px"
              />
            </el-form-item>
            <el-form-item label="账单周期" style="margin-right:20px">
              <el-date-picker
                v-model="daterange"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width:260px"
                @change="selectDaterange"
              />
            </el-form-item>
            <el-form-item label="本期留存金额：$" prop="balance" label-width="108px">
              <el-input v-model="billForm.balance" placeholder="请填写金额" style="width:150px" />
            </el-form-item>
          </div>

          <el-form-item label="收入明细">
            <el-button plain type="primary" icon="el-icon-plus" class="form-btn nonbg-btn" @click="addIncomeItem">添加</el-button>
          </el-form-item>
          <el-form-item v-for="(item, index) in incomeList" :key="`in-${index}`">
            <el-select v-model="item.itemId" filterable placeholder="请选择收入明目" style="width:150px;margin-right:20px;">
              <el-option
                v-for="option in incomeItemList"
                :key="option.id"
                :label="option.name"
                :value="option.id"
              />
            </el-select>
            <div class="dollar">$</div>
            <el-input v-model="item.fee" placeholder="请填写金额" style="width:150px;margin-right:20px;" type="number" class="no-number" @change="getTotalIn" />
            <bill-item-file
              v-if="showAdd"
              v-model="item.filePath"
              dir="monthly"
              name="上传凭证"
              :maxcount="1000"
              format="png,pdf,jpg,jpeg"
              :urls="item.filePath"
              @getFile="getInItemFile($event, index)"
            />
            <i v-if="index > 0" class="el-icon-remove-outline" @click="deleteIncomeItem(item, index)" />
          </el-form-item>

          <el-form-item label="支出明细">
            <el-button plain type="primary" icon="el-icon-plus" class="form-btn nonbg-btn" @click="addOutcomeItem">添加</el-button>
          </el-form-item>
          <el-form-item v-for="(item, index) in outcomeList" :key="`out-${index}`">
            <el-select v-model="item.itemId" filterable placeholder="请选择支出明目" style="width:150px;margin-right:20px;">
              <el-option
                v-for="option in outcomeItemList"
                :key="option.id"
                :label="option.name"
                :value="option.id"
              />
            </el-select>
            <div class="dollar">$</div>
            <el-input v-model="item.fee" placeholder="请填写金额" style="width:150px;margin-right:20px;" type="number" class="no-number" @change="getTotalOut" />
            <bill-item-file
              v-if="showAdd"
              v-model="item.filePath"
              dir="monthly"
              name="上传凭证"
              :maxcount="1000"
              format="png,pdf,jpg,jpeg"
              :urls="item.filePath"
              @getFile="getOutItemFile($event, index)"
            />
            <i v-if="index > 0" class="el-icon-remove-outline" @click="deleteOutcomeItem(item, index)" />
          </el-form-item>

          <el-form-item label="备注说明">
            <el-input v-model="billForm.remark" :rows="4" type="textarea" placeholder="请输入..." />
            <div class="form-note-text">
              收入：${{ totalIn }}<span style="display:inline-block;width:10px;" />
              往期留存：${{ pastBalance }}<span style="display:inline-block;width:10px;" />
              支出：${{ totalOut }}<span style="display:inline-block;width:10px;" />
              结余：${{ remain }}</div>
          </el-form-item>

          <el-form-item label="其他">
            <bill-file-upload
              v-if="showAdd"
              v-model="billForm.filePath"
              dir="monthly"
              name="上传英文账单"
              :maxcount="1000"
              format="png,pdf,jpg,jpeg"
              :urls="billForm.filePath"
              @getFile="getFile"
            />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!isEdit" plain type="primary" class="dialog-footer-btn white-bg-btn" @click="saveBill">保存</el-button>
        <el-button v-else-if="isEdit && billForm.status === 0" plain type="primary" class="dialog-footer-btn white-bg-btn" @click="editBill(0)">保存</el-button>
        <el-button v-else plain type="primary" class="dialog-footer-btn white-bg-btn" @click="editBill(1)">保存</el-button>
        <el-button v-if="!isEdit" type="primary" class="dialog-footer-btn" @click="sendBill">确认发出</el-button>
        <el-button v-if="isEdit && billForm.status === 0" type="primary" class="dialog-footer-btn" @click="editBill(1)">确认发出</el-button>
        <el-button type="info" class="dialog-footer-btn" @click="close">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title=""
      width="650px"
      custom-class="myDigo inputTop"
      :show-close="false"
      :visible.sync="showDel"
    >
      <h2>确认删除<i class="el-icon-close" @click="showDel = false" /></h2>
      <div class="digoDiv">
        <div class="dialog-content flex-row">
          <svg-icon class="warning-icon" icon-class="warning" /><span class="dialog-tip-text">确认删除该条月账单吗？</span>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" class="dialog-footer-btn" @click="delBill(tempBillId)">确认</el-button>
        <el-button type="info" class="dialog-footer-btn" @click="showDel = false">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title=""
      width="1073px"
      custom-class="billDialog"
      :visible.sync="showLastBill"
    >
      <last-bill :bill-info="lastBillInfo" />
    </el-dialog>
  </div>
</template>

<script>
import { pageByOperation } from '@/api/house'
import { getFinanceCatalogList } from '@/api/dataConfig'
import { addBill, getBillList, delBill, billDetail, editBill, recentBill } from '@/api/billing'
import MonthlyTable from './MonthlyTable.vue'
import BillFileUpload from '@/components/Upload/BillFileUpload.vue'
import BillItemFile from '@/components/Upload/BillItemFile.vue'
import LastBill from './LastBill.vue'
export default {
  components: { MonthlyTable, BillFileUpload, BillItemFile, LastBill },
  data() {
    const checkFee = (rule, value, callback) => {
      if (!value || +value === 0) {
        callback()
      }
      if (!Number(value * 1)) {
        callback(new Error('请输入数字值'))
      } else {
        if (value * 1 > 999999) {
          callback(new Error('金额不大于999999'))
        } else {
          callback()
        }
      }
    }
    return {
      daterange: [],
      value: '',
      houseList: [],
      incomeItemList: [],
      outcomeItemList: [],
      extraData: {},
      houseListQuery: {
        page: 1,
        limit: 10000
      },
      listQuery: {
        keyword: undefined,
        billDate: undefined,
        property: undefined,
        status: undefined
      },
      billList: [],
      tableListQuery: {
        page: 1,
        limit: 10,
        keyword: undefined,
        billDate: undefined,
        status: undefined
      },
      loading: false,
      total: 0,
      showAdd: false,
      showDel: false,
      showLastBill: false,
      isEdit: false,
      defaultForm: {
        type: 0,
        houseId: '',
        billDate: '',
        beginDate: '',
        endDate: '',
        balance: undefined,
        pastBalance: undefined,
        status: 0,
        detailList: [],
        remark: '',
        filePath: ''
      },
      billForm: {
        type: 0,
        houseId: '',
        billDate: '',
        beginDate: '',
        endDate: '',
        balance: undefined,
        pastBalance: undefined,
        status: 0,
        detailList: [],
        remark: '',
        filePath: ''
      },
      rules: {
        balance: [{ validator: checkFee, trigger: 'blur' }]
      },
      incomeList: [{
        financeType: 'INCOME',
        name: '',
        itemId: '',
        fee: undefined,
        filePath: ''
      }],
      outcomeList: [{
        financeType: 'EXPEND',
        name: '',
        itemId: '',
        fee: undefined,
        filePath: ''
      }],
      tempBillId: undefined,
      lastBillInfo: {},
      pastBalance: 0,
      totalIn: 0,
      totalOut: 0
    }
  },
  computed: {
    remain() {
      return (this.totalIn * 1 + this.pastBalance * 1 - this.totalOut * 1 - (this.billForm.balance * 1 || 0)).toFixed(2)
    }
  },
  created() {
    this.getBillList()
    if (this.$route.query.houseId) {
      this.billForm.houseId = this.$route.query.houseId
      this.billForm.billDate = `${this.$route.query.billDate}-01`
      console.log(`${this.$route.query.billDate}-01`)
      this.addBillClick()
    }
  },
  methods: {
    async addBillClick() {
      await this.getHouseList()
      await this.getIncomeItemList()
      await this.getOutcomeItemList()
      this.showAdd = true
    },
    close() {
      this.showAdd = false
    },
    billDetail(id) {
      const routeUrl = this.$router.resolve({ path: '/view', query: { billId: id, type: '1' }})
      window.open(routeUrl.href, '_blank')
    },
    addDialogClosed() {
      this.billForm = { ...this.defaultForm }
      this.daterange = []
      this.isEdit = false
      this.incomeList = [{
        financeType: 'INCOME',
        name: '',
        itemId: '',
        fee: undefined,
        filePath: ''
      }]
      this.outcomeList = [{
        financeType: 'EXPEND',
        name: '',
        itemId: '',
        fee: undefined,
        filePath: ''
      }]
      this.pastBalance = 0
      this.totalIn = 0
      this.totalOut = 0
    },
    getBillList() {
      this.loading = true
      getBillList(this.tableListQuery).then(response => {
        this.billList = response.data.page.records
        this.total = response.data.page.total
        this.extraData = response.data.extraData || {}
        this.loading = false
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.tableListQuery.page = 1
      this.tableListQuery.limit = val
      this.getBillList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.tableListQuery.page = val
      this.getBillList()
    },
    selectHouse(val) {
      console.log(val)
      this.pastBalance = 0
      this.getPastBalance(val)
    },
    selectDaterange(list) {
      this.billForm.beginDate = list[0]
      this.billForm.endDate = list[1]
    },
    async getHouseList() {
      const res = await pageByOperation(this.houseListQuery)
      if (res.code === 200) {
        this.houseList = res.data.records
      }
    },
    saveBill() {
      this.billForm.status = 0
      this.billForm.detailList = [...this.incomeList, ...this.outcomeList]
      addBill(this.billForm).then(response => {
        this.showAdd = false
        this.getBillList()
        this.$notify({
          title: '成功',
          message: '添加成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    sendBill() {
      this.billForm.status = 1
      this.billForm.detailList = [...this.incomeList, ...this.outcomeList]
      addBill(this.billForm).then(response => {
        this.showAdd = false
        this.getBillList()
        this.$notify({
          title: '成功',
          message: '添加成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    editBill(status) {
      this.billForm.status = status
      this.billForm.detailList = [...this.incomeList, ...this.outcomeList]
      editBill({ ...this.billForm, id: this.tempBillId }).then(response => {
        this.showAdd = false
        this.getBillList()
        this.$notify({
          title: '成功',
          message: '编辑成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleDel(id) {
      this.showDel = true
      this.tempBillId = id
    },
    delBill(id) {
      delBill(id).then(response => {
        this.showDel = false
        this.getBillList()
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    addIncomeItem() {
      this.incomeList.push({
        financeType: 'INCOME',
        name: '',
        itemId: '',
        fee: undefined,
        filePath: ''
      })
      console.log(this.incomeList)
    },
    addOutcomeItem() {
      this.outcomeList.push({
        financeType: 'EXPEND',
        name: '',
        itemId: '',
        fee: undefined,
        filePath: ''
      })
      console.log(this.outcomeList)
    },
    deleteIncomeItem(item, index) {
      this.incomeList.splice(index, 1)
    },
    deleteOutcomeItem(item, index) {
      this.outcomeList.splice(index, 1)
    },
    async getIncomeItemList() {
      const params = {
        type: 0,
        financeType: 1
      }
      const res = await getFinanceCatalogList(params)
      if (res.code === 200) {
        this.incomeItemList = res.data
      }
    },
    async getOutcomeItemList() {
      const params = {
        type: 0,
        financeType: 0
      }
      const res = await getFinanceCatalogList(params)
      if (res.code === 200) {
        this.outcomeItemList = res.data
        console.log(this.outcomeItemList)
      }
    },
    async edit(id) {
      const res = await billDetail(id)
      if (res.code === 200) {
        this.tempBillId = id
        this.isEdit = true
        await this.getHouseList()
        await this.getIncomeItemList()
        await this.getOutcomeItemList()
        Object.keys(this.billForm).map(i => {
          this.billForm[i] = res.data[i]
        })
        this.incomeList = (res.data.detailList.filter(item => item.financeType === 1)).length > 0 ? res.data.detailList.filter(item => item.financeType === 1) : this.incomeList
        this.outcomeList = (res.data.detailList.filter(item => item.financeType === 0)).length > 0 ? res.data.detailList.filter(item => item.financeType === 0) : this.outcomeList
        this.daterange = [this.billForm.beginDate, this.billForm.endDate]
        // this.selectHouse(this.billForm.houseId)
        this.pastBalance = this.billForm.pastBalance
        this.getTotalIn()
        this.getTotalOut()
        this.showAdd = true
      }
    },
    async getLastBill(id) {
      if (!id) {
        this.$message({ message: '请先选择房产', type: 'error' })
        return false
      }
      const billDate = this.billForm.billDate || null
      const type = this.isEdit ? 1 : 0
      const params = {
        billId: this.tempBillId,
        houseId: id,
        type,
        billDate
      }
      const res = await recentBill(params)
      if (res.code === 200) {
        console.log(res)
        this.lastBillInfo = res.data || {}
        if (res.data && res.data.address) {
          this.showLastBill = true
        } else {
          this.$message({ message: '暂无最近账单', type: 'warning' })
        }
      }
    },
    async getPastBalance(id) {
      if (!id) {
        return false
      }
      const type = this.isEdit ? 1 : 0
      const params = {
        billId: this.tempBillId,
        houseId: id,
        type
      }
      const res = await recentBill(params)
      if (res.code === 200) {
        if (!res.data) {
          this.pastBalance = 0
          return false
        }
        this.pastBalance = res.data.balance || 0
        console.log('pastBalance', this.pastBalance)
      }
    },
    getFile(val) {
      console.log('val.toString():', val.toString())
      this.billForm.filePath = val.toString()
    },
    getInItemFile(val, index) {
      console.log('val.toString():', val.toString())
      this.incomeList[index].filePath = val.toString()
    },
    getOutItemFile(val, index) {
      console.log('val.toString():', val.toString())
      this.outcomeList[index].filePath = val.toString()
    },
    getTotalIn() {
      this.totalIn = 0
      this.incomeList.forEach(item => {
        if (item.fee) {
          this.totalIn = this.totalIn + item.fee * 1
        }
      })
      this.totalIn = this.totalIn.toFixed(2)
    },
    getTotalOut() {
      this.totalOut = 0
      this.outcomeList.forEach(item => {
        if (item.fee) {
          this.totalOut = this.totalOut + item.fee * 1
        }
      })
      this.totalOut = this.totalOut.toFixed(2)
    },
    ceil(num, byte) {
      const absNum = Math.abs(num)
      const n = Math.pow(10, byte)
      return num > 0 ? parseInt(absNum * n) / n : 0 - parseInt(absNum * n) / n
    }
  }
}
</script>

<style lang="scss">
.monthly-container {
  .no-number::-webkit-outer-spin-button,
  .no-number::-webkit-inner-spin-button {
    margin: 0;
    -webkit-appearance: none !important;
  }

  .no-number input[type="number"]::-webkit-outer-spin-button,
  .no-number input[type="number"]::-webkit-inner-spin-button {
    margin: 0;
    -webkit-appearance: none !important;
  }

  /*在firefox下移除input[number]的上下箭头*/
  .no-number {
    -moz-appearance: textfield;
  }

  .no-number input[type="number"] {
    -moz-appearance: textfield;
  }
}

</style>

<style lang="scss" scoped>
.monthly-container {
  padding-right: 10px;
}

.bill-overview {
  height: 20px;
  color: rgb(140, 140, 140);
  font-size: 14px;
  line-height: 20px;
  margin-bottom: 20px;
}

.dollar {
  display: inline-block;
  padding: 0 8px;
  color: #101010;
  font-size: 12px;
  font-weight: normal;
}

.myDigo h2 {
  height: 32px;
  background: #343436;
}

.form-btn {
  height: 32px;
  padding: 0 12px;
  font-size: 12px;
}

::v-deep .myDigo .el-dialog__footer {
  background: #e5e9ed;
  padding-top: 20px;
}

::v-deep .el-dialog.myDigo .el-dialog__body {
  padding: 0;
}

::v-deep .el-dialog.myDigo .el-dialog__header {
  display: none;
}

::v-deep .el-dialog.billDialog .el-dialog__body {
  padding: 0 40px;
}

::v-deep .el-dialog.billDialog .el-dialog__header {
  padding: 0;
}

.el-dialog.myDigo h2 {
  height: 58px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 39px;
  padding-right: 39px;
  color: #fff;
  font-size: 18px;
  padding-top: 0;
  margin-top: 0;
  overflow: hidden;
  font-weight: normal;
  font-family: "SourceHanSansSC-regular";
}

.el-dialog.myDigo h2 i {
  font-size: 26px;
  cursor: pointer;
}

::v-deep .el-dialog.myDigo .el-dialog__body {
  text-align: left;
}

.digoDiv ::v-deep .el-input--medium .el-input__inner {
    height: 32px;
    line-height: 32px;
    text-indent: 5px;
}

::v-deep .inputTop input::-webkit-input-placeholder,
textarea::-webkit-input-placeholder,
select::-webkit-input-placeholder {
  font-size: 12px;
}

::v-deep .inputTop input:-moz-placeholder,
textarea:-moz-placeholder,
select::-webkit-input-placeholder {
  font-size: 12px;
}

::v-deep .inputTop input::-moz-placeholder,
textarea::-moz-placeholder,
select::-webkit-input-placeholder {
  font-size: 12px;
}

::v-deep .inputTop input:-ms-input-placeholder,
textarea:-ms-input-placeholder,
select::-webkit-input-placeholder {
  font-size: 12px;
}

::v-deep .el-form-item {
  margin-bottom: 16px;
}

::v-deep .el-form-item--medium .el-form-item__label {
  color: #101010;
  font-size: 12px;
  font-weight: bold;
}

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
input[type="number"]{
  -moz-appearance: none !important;
}

.nonbg-btn {
  background: none;
}

.mtright {
  margin-right: 11px;
}

.formDiv {
  height: 600px;
  padding-left: 39px;
  padding-right: 39px;
  overflow: scroll;
}

.borbtoonline {
  padding-bottom: 20px;
  margin-bottom: 20px;
  position: relative;
}

.borbtoonline::after {
  content: "";
  position: absolute;
  left: -51px;
  bottom: 0;
  width: 111%;
  height: 1px;
  background: #f0f0f0;
}

.borbtoonline .el-form-item {
  margin-bottom: 0;
}

.el-icon-remove-outline {
  margin-left: 20px;
  display: inline-block;
  color: #5AC6B7;
  font-weight: bold;
  transform: scale(1.5);
}

.white-bg-btn {
  background: #fff;
}

.dialog-footer-btn {
  width: 100px;
}

.form-note-text {
  font-size: 12px;
  font-weight: bold;
  color: #101010;
}

.dialog-content {
  height: 150px;
  padding: 0 60px;
  align-items: center;
}

.warning-icon {
  margin-right: 20px;
  height: 24px;
  width: 24px;
  fill: #F45656;
}

.dialog-tip-text {
  display: inline-block;
  font-size: 18px;
  height: 24px;
  line-height: 24px;
  color: rgba(28, 28, 28, 100);
}
</style>
